package com.xkcyy.one.ai.tools;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xkcyy.one.ai.common.tool.AbstractSimpleTool;
import com.xkcyy.one.ai.common.tool.ToolArguments;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class ListDirectoryTool extends AbstractSimpleTool<ListDirectoryTool.Arguments> {
    
    @Override
    public String getName() {
        return "list_directory";
    }

    @Override
    public String getDescription() {
        return "列出指定目录下的所有文件和子目录";
    }

    @Override
    public String doExecute(Arguments arguments) {
        try {
            File directory = new File(arguments.getPath());
            if (!directory.exists() || !directory.isDirectory()) {
                throw new IllegalArgumentException("指定的路径不存在或不是一个目录: " + arguments.getPath());
            }

            File[] files = directory.listFiles();
            if (files == null) {
                return "[]";
            }

            List<FileInfo> fileInfos = Arrays.stream(files)
                    .map(file -> new FileInfo(
                            file.getName(),
                            file.isDirectory(),
                            file.length(),
                            file.lastModified()
                    ))
                    .collect(Collectors.toList());

            return new ObjectMapper().writeValueAsString(fileInfos);
        } catch (Exception e) {
            log.error("Failed to list directory: {}", arguments.getPath(), e);
            throw new RuntimeException("Failed to list directory: " + e.getMessage(), e);
        }
    }

    @Data
    @EqualsAndHashCode(callSuper = true)
    public static class Arguments extends ToolArguments {
        /**
         * 要读取的目录路径
         */
        private String path;
    }

    @Data
    private static class FileInfo {
        private final String name;
        private final boolean isDirectory;
        private final long size;
        private final long lastModified;
    }
} 